#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include "sens_receiver.h"

/* The function that is called for each received
 * packet of sensor data.
 */
int show_packet(tsens_data sens_data) {
  show_sens_data(sens_data); /* just show it on stdout */
  printf("\n");
  return 0;
}

/* stop with Ctrl-C */
void ctrlc(int sig) {
  printf("caught SIGINT, stop_receiving\n");
  stop_polling(SENS_PORT);
  printf("receiving stopped\n");
}

/* Accepting packets and make them available svia polling.
 * First parameter is number of polls per second, 20 default.
 * End the program with CTRL-C
 */
int main(int argc, char *argv[]) {
  int polls_per_second = 20;
  struct timespec sleep_time;

  printf("%s n    n=number of polls per second\n", argv[0]);
  if (argc == 2)
    polls_per_second = atoi(argv[1]);
  /* open the connection and prepare for polling */
  if (start_polling(SENS_PORT) != 0) { 
    printf("opening sensor failed");
    return -1;
  }
  printf("receiving packets and polling. Ctrl-C to stop\n");
  sleep_time.tv_sec = 0;
  sleep_time.tv_nsec = (1.0 / polls_per_second)*1000000000;
  printf("receiving a packet every %ld milliseconds\n", sleep_time.tv_nsec/1000000);
  /* receiving in separate thread with timeout */
  signal(SIGINT, ctrlc);  /* stop receiving on Ctrl-C */
  while (1) { /* is_receiving is allowed */
    tsens_data packet = sens_poll(SENS_PORT);
    show_packet(packet);
    if (nanosleep(&sleep_time, NULL) != 0) 
      break;    
  }
  return 0;
}
